package com.btex.app;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btex.app.entity.OTCBuyAndSellOrderBean;
import com.btex.app.entity.OTCBuyBean;
import com.btex.app.entity.OtcSellInfo;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.OTCSellConfirmDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Tools;
import com.btex.app.tools.Util;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OTCSellActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_menu)
    TextView mTvMenu;
    @BindView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.otc_activity_tv_danhao)
    TextView mOtcActivityTvDanhao;
    @BindView(R.id.otc_activity_tv_name)
    TextView mOtcActivityTvName;
    @BindView(R.id.otc_activity_tv_xian_e)
    TextView mOtcActivityTvXianE;
    @BindView(R.id.otc_activity_tv_money)
    TextView mOtcActivityTvMoney;
    @BindView(R.id.otc_activity_ed_number)
    EditText mOtcActivityEdNumber;
    @BindView(R.id.otc_activity_ed_price)
    EditText mOtcActivityEdPrice;
    @BindView(R.id.otc_activity_ed_password)
    EditText mOtcActivityEdPassword;
    @BindView(R.id.otc_activity_but_sure)
    Button mOtcActivityButSure;
    @BindView(R.id.otc_activity_lin_bank)
    LinearLayout mOtcActivityLinBank;
    @BindView(R.id.otc_activity_lin_zhi)
    LinearLayout mOtcActivityLinZhi;
    @BindView(R.id.otc_activity_lin_wei)
    LinearLayout mOtcActivityLinWei;
    @BindView(R.id.otc_activity_imag_bank)
    ImageView mOtcActivityImagBank;
    @BindView(R.id.otc_activity_imag_zhi)
    ImageView mOtcActivityImagZhi;
    @BindView(R.id.otc_activity_imag_wei)
    ImageView mOtcActivityImagWei;
    @BindView(R.id.otc_activity_tv_price)
    TextView mOtcActivityTvPrice;
    @BindView(R.id.otc_activity_lin_money)
    LinearLayout mOtcActivityLinMoney;
    @BindView(R.id.tv_otc_la)
    ImageView mTvOtcLa;
    @BindView(R.id.otc_activity_tv_danprice)
    TextView mOtcActivityTvDanprice;
    @BindView(R.id.otc_activity_ed_nume_type)
    TextView mOtcActivityEdNumeType;
    @BindView(R.id.otc_activity_ed_price_type)
    TextView mOtcActivityEdPriceType;
    @BindView(R.id.otc_activity_imag_tyd)
    ImageView mOtcActivityImagTyd;
    @BindView(R.id.otc_activity_lin_tyd)
    LinearLayout mOtcActivityLinTyd;
    private OTCBuyAndSellOrderBean.DataBean.BidsBean mData;

    private boolean flag = true;

    public String type = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otcbuy_and_sell);
        ButterKnife.bind(this);
//        EventBus.getDefault().register(this);
//        mTvTitle.setText("卖出USDT");


        mData = (OTCBuyAndSellOrderBean.DataBean.BidsBean) getIntent().getExtras().get("data");
        String type = mData.getType();

        if (mData.getType().equals("USDT")) {
            mTvTitle.setText("卖出"+type);
            initUSDTInfo(type);
        } else {
            mTvTitle.setText("卖出"+type);
            initUSDTInfo(type);
        }
        initView(mData);
        initListener();


    }


    private void initUSDTInfo(final String type) {
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(this, SharedPreferencesUtil.getSharedPreferences(this));
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type", type);
        params.addHeader("myclient", "android");
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.URL_MY_COINS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                String reuslt = responseInfo.result.toString();

                try {
                    JSONObject jsonObject = new JSONObject(reuslt);

                    if (jsonObject.getString(Config.KEY_CODE).equals("1")) {
                        Gson gson = new Gson();
                        OtcSellInfo myInfoListInfo = gson.fromJson(reuslt, OtcSellInfo.class);
                        String total_guzhi_usdt = myInfoListInfo.getData().getBalance();

                        if (type.equals("USDT")) {
                            mOtcActivityTvMoney.setText(total_guzhi_usdt + "\t" + type);
                        } else {
                            mOtcActivityTvMoney.setText(total_guzhi_usdt + "\t" + type);
                        }


                    } else {
                        Toast.makeText(getApplicationContext(), jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }

    private void initView(OTCBuyAndSellOrderBean.DataBean.BidsBean data) {


        String types = data.getType();
        String danwei = data.getDanwei();

        if ("TYD".equals(types)) {
            mOtcActivityEdNumeType.setText(types);
            mOtcActivityEdPriceType.setText(danwei);
            mOtcActivityTvDanprice.setText(danwei);
            mOtcActivityTvXianE.setText(data.getMin_limit_total() + "~" + data.getMax_limit_total() + "\t" + danwei);
        } else {
            mOtcActivityEdNumeType.setText(types);
            mOtcActivityEdPriceType.setText(danwei);
            mOtcActivityTvDanprice.setText(danwei);
            String s = Tools.round(Double.valueOf(data.getMin_limit_total()), 2).toString();
            String s1 = Tools.round(Double.valueOf(data.getMax_limit_total()), 2).toString();
            mOtcActivityTvXianE.setText(s + "~" + s1 + "\t" + danwei);
        }

        List<String> pay_type = data.getPay_type();
        if (pay_type.contains("weixin")) {
            mOtcActivityLinWei.setVisibility(View.VISIBLE);
        } else {
            mOtcActivityLinWei.setVisibility(View.GONE);
        }

        if (pay_type.contains("bank")) {
            mOtcActivityLinBank.setVisibility(View.VISIBLE);
        } else {
            mOtcActivityLinBank.setVisibility(View.GONE);
        }

        if (pay_type.contains("alipay")) {
            mOtcActivityLinZhi.setVisibility(View.VISIBLE);

        } else {
            mOtcActivityLinZhi.setVisibility(View.GONE);
        }


        if (pay_type.contains("tianya")) {
            mOtcActivityLinTyd.setVisibility(View.VISIBLE);

        } else {
            mOtcActivityLinTyd.setVisibility(View.GONE);
        }


        mOtcActivityTvDanhao.setText("订单号:" + "\t" + data.getOrder_id());
        mOtcActivityTvName.setText(data.getTrue_name());

//        mOtcActivityTvMoney.setText(data.getRest_num() + "\t" + "USDT");

        mOtcActivityTvPrice.setText(data.getPrice().substring(0, 4));
    }


    private void initListener() {
        mOtcActivityEdPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {

                String trim = s.toString().trim();

                if (!TextUtils.isEmpty(trim)) {

                    double v = Double.parseDouble(trim);
                    if (mData != null) {

                        String price = mData.getPrice();
                        double v1 = Double.parseDouble(price);
                        double div = div(v, v1, 2);
                        String s1 = String.valueOf(div);

                        if (flag) {
                            flag = false;
                            mOtcActivityEdNumber.setText(s1);

                        } else {
                            flag = true;
                        }


                    }


                } else {

                    if (flag) {
                        flag = false;
                        mOtcActivityEdNumber.setText("");

                    } else {
                        flag = true;
                    }

                }


            }
        });


        mOtcActivityEdNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {


                String trim = s.toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    if (mData != null) {
                        String price = mData.getPrice();
                        double v1 = Double.parseDouble(price);
                        double v = Double.parseDouble(trim);
                        double mul = mul(v1, v);
//                        if (isDownnumber) {
//                            Log.i("kdhqwiduhqidw", "1");
//                            mOtcActivityEdPrice.setText(String.valueOf(mul));
//                        }
                        if (flag) {
                            flag = false;
                            mOtcActivityEdPrice.setText(String.valueOf(mul));

                        } else {
                            flag = true;
                        }


                    }


                } else {

                    if (flag) {
                        flag = false;
                        mOtcActivityEdPrice.setText("");

                    } else {
                        flag = true;
                    }

                }
            }
        });
    }


    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {

    }


    @OnClick({R.id.otc_activity_lin_bank, R.id.otc_activity_lin_zhi, R.id.otc_activity_lin_wei, R.id.iv_back, R.id.otc_activity_but_sure, R.id.otc_activity_lin_tyd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.otc_activity_lin_bank:
                type = "bank";
                setStatus();
                mOtcActivityImagBank.setBackgroundResource(R.mipmap.otc_xuanzhe);
                break;
            case R.id.otc_activity_lin_zhi:
                type = "alipay";
                setStatus();
                mOtcActivityImagZhi.setBackgroundResource(R.mipmap.otc_xuanzhe);
                break;
            case R.id.otc_activity_lin_wei:
                type = "weixin";
                setStatus();
                mOtcActivityImagWei.setBackgroundResource(R.mipmap.otc_xuanzhe);
                break;

            case R.id.iv_back:
                finish();
                break;
            case R.id.otc_activity_but_sure:


                String number = mOtcActivityEdNumber.getText().toString().trim();
                String price = mOtcActivityEdPrice.getText().toString().trim();
                String password = mOtcActivityEdPassword.getText().toString().trim();
                if (number.isEmpty()) {
//                    SnackbarShow("交易数量不能为空");

                    Util.showSnachBar(OTCSellActivity.this, getResources().getColor(R.color.red), "交易数量不能为空");

                    return;
                }
                if (price.isEmpty()) {
//                    SnackbarShow("交易总价不能为空");
                    Util.showSnachBar(OTCSellActivity.this, getResources().getColor(R.color.red), "交易总价不能为空");
                    return;
                }
                if (password.isEmpty()) {
//                    SnackbarShow("交易密码不能为空");
                    Util.showSnachBar(OTCSellActivity.this, getResources().getColor(R.color.red), "交易密码不能为空");
                    return;
                }
                if (type.equals("")) {
//                    SnackbarShow("付款方式不能为空");
                    Util.showSnachBar(OTCSellActivity.this, getResources().getColor(R.color.red), "付款方式不能为空");
                    return;
                }


                OTCBuyBean otcBuyBean = new OTCBuyBean();
                otcBuyBean.num = number;
                otcBuyBean.price = price;
                otcBuyBean.password = password;
                otcBuyBean.danhao = mData.getOrder_id();
                otcBuyBean.name = mData.getTrue_name();
                otcBuyBean.type = type;

                new OTCSellConfirmDialog(this, mData, otcBuyBean).show();

                break;

            case R.id.otc_activity_lin_tyd:

                type = "tianya";
                setStatus();
                mOtcActivityImagTyd.setBackgroundResource(R.mipmap.otc_xuanzhe);

                break;

        }
    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEvent(String event) {
//        if ("otc".equals(event)) {
//
//
//            Toast.makeText(cxt, "购买", Toast.LENGTH_SHORT).show();
//        }
//    }

    private void setStatus() {
        mOtcActivityImagBank.setBackgroundResource(R.mipmap.otc_nomal_xuan);
        mOtcActivityImagZhi.setBackgroundResource(R.mipmap.otc_nomal_xuan);
        mOtcActivityImagWei.setBackgroundResource(R.mipmap.otc_nomal_xuan);
    }


//    private void SnackbarShow(String ms) {
//
//        Snackbar snackbar = ShortSnackbar(mOtcActivityButSure, ms, Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//        snackbar.show();
//    }
//
//    public static Snackbar ShortSnackbar(View view, String message, int messageColor, int backgroundColor) {
//        Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_SHORT);
//        setSnackbarColor(snackbar, messageColor, backgroundColor);
//        return snackbar;
//    }
//
//    /**
//     * 设置Snackbar文字和背景颜色
//     *
//     * @param snackbar
//     * @param messageColor
//     * @param backgroundColor
//     */
//    public static void setSnackbarColor(Snackbar snackbar, int messageColor, int backgroundColor) {
//        View view = snackbar.getView();
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//
//            TextView message = (TextView) snackbar.getView().findViewById(R.id.snackbar_text);
//            //View.setTextAlignment需要SDK>=17
//            message.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY);
//            message.setGravity(Gravity.CENTER);
//        }
//
//        if (view != null) {
//            view.setBackgroundColor(backgroundColor);
//            ((TextView) view.findViewById(R.id.snackbar_text)).setTextColor(messageColor);
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     *
     * @param v1    被除数
     * @param v2    除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 提供精确乘法运算的mul方法
     *
     * @param value1 被乘数
     * @param value2 乘数
     * @return 两个参数的积
     */
    public static double mul(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.multiply(b2).doubleValue();
    }
}
